class Api::AppController < ApplicationController

  # 处理新闻信息请求的控制器方法
  def news
    conditions = {}
    conditions[:news_category_id] = params[:news_category_id] if params[:news_category_id].present?
    conditions[:id] = params[:last] if params[:last].present?

    @news = News
              .where(conditions)
              .order(id: :desc)
              .includes(:user, comments: :user)
              .paginate(page: pagination_params[:page], per_page: pagination_params[:per_page])

    render json: ApiResponse.success(
      data: pagination_meta.merge(data: @news.as_json(include: { user: {}, comments: { include: :user } }))
    )
  end

  private
  # 分页参数处理
  def pagination_params
    {
      page: [ params[:page].to_i, 1 ].max,
      per_page: [ [ params[:per_page].to_i, 2 ].max, 100 ].min
    }
  end

  # 分页元数据构建
  def pagination_meta
    {
      total: @news.total_entries,
      pages: @news.total_pages,
      size: @news.limit_value,
      page: @news.current_page
    }
  end

end
